package com.jianguozh.difs.support.service.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jianguozh.difs.support.service.sys.entity.Client;
import com.jianguozh.difs.support.service.sys.entity.Res;
import com.jianguozh.difs.support.service.sys.entity.Role;
import com.jianguozh.difs.support.service.sys.mapper.RoleMapper;
import com.jianguozh.difs.support.service.sys.service.IRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author hanrs
 * @since 2022-03-17
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Override
    @Transactional
    public boolean removeById(Serializable id) {
        getBaseMapper().deleteRoleUser(id);
        getBaseMapper().deleteRoleAllClient(id);
        getBaseMapper().deleteRoleRes(id);
        return super.removeById(id);
    }

    @Override
    public List<Client> listGrantedClient(String roleId) {
        return getBaseMapper().selectListGrantedClient(roleId);
    }

    @Override
    public List<Res> listGrantedRes(String roleId, String clientId) {
        return getBaseMapper().selectListGrantedRes(roleId, clientId);
    }

    @Override
    public List<Role> listByClientId(String clientId) {
        return getBaseMapper().selectListByClientId(clientId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGrantedClientAndRes(String roleId, String clientId, Boolean granted, List<String> resIds) {

        getBaseMapper().deleteRoleClient(roleId, clientId);
        getBaseMapper().deleteRoleClientRes(roleId, clientId);

        if (granted) {
            getBaseMapper().insertRoleClient(roleId, clientId);
            if (resIds.size() > 0) {
                getBaseMapper().insertRoleRes(roleId, resIds);
            }
        }
    }
}
